package com.yang.core.client;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yang.core.config.RestClientConfig;
import com.yang.core.model.ResponseContext;
import com.yang.core.model.HttpResponse;
import com.yang.core.api.RestClientException;
import com.yang.demo.util.JsonUtils;

import java.lang.reflect.Type;

/**
 * 响应处理器
 */
public class ResponseProcessor {

    private final RestClientConfig config;

    public ResponseProcessor(RestClientConfig config) {
        this.config = config;
    }

    /**
     * 处理响应
     */
    @SuppressWarnings("unchecked")
    public <T> HttpResponse<T> process(ResponseContext responseContext, Class<T> responseType) {
        HttpResponse<T> response = HttpResponse.<T>builder()
                .statusCode(responseContext.getStatusCode())
                .responseTime(responseContext.getResponseTime())
                .build();

        if (responseContext.getBody() != null && !responseContext.getBody().isEmpty()) {
            try {
                if (responseType == String.class) {
                    response.setData((T) responseContext.getBody());
                } else {
                    T data = JsonUtils.fromJson(responseContext.getBody(), responseType);
                    response.setData(data);
                }
            } catch (Exception e) {
                throw new RestClientException("响应解析失败", e);
            }
        }

        return response;
    }

    /**
     * 处理响应（泛型版本）
     */
    @SuppressWarnings("unchecked")
    public <T> HttpResponse<T> process(ResponseContext responseContext, Type responseType) {
        HttpResponse<T> response = HttpResponse.<T>builder()
                .statusCode(responseContext.getStatusCode())
                .responseTime(responseContext.getResponseTime())
                .build();

        if (responseContext.getBody() != null && !responseContext.getBody().isEmpty()) {
            try {
                T data = JsonUtils.fromJson(responseContext.getBody(), new TypeReference<T>() {
                    @Override
                    public Type getType() {
                        return responseType;
                    }
                });
                response.setData(data);
            } catch (Exception e) {
                throw new RestClientException("响应解析失败", e);
            }
        }

        return response;
    }
}